package com.xiaotu.service.Impl;

import com.xiaotu.pojo.Authority;
import com.xiaotu.pojo.Customer;
import com.xiaotu.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    @Qualifier(value = "jpaCustomerServiceImpl")
    private CustomerService customerService;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //通过业务方法获取用户及权限信息
        Customer customer = customerService.getCustomer(s);
        List<Authority> customerAuthority = customerService.getCustomerAuthority(s);
        //对用户权限进行封装
        List<SimpleGrantedAuthority> list = customerAuthority.stream().map(authority -> new SimpleGrantedAuthority(authority.getAuthority()))
                .collect(Collectors.toList());
        //返回封装的UserDetails用户详情类
        if(customer!=null){
            User user = new User(customer.getUsername(), customer.getPassword(), list);
            return user;
        }else{
            throw new UsernameNotFoundException("当前用户不存在");
        }
    }
}
